package fa7.socialcode.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.TopicoDao;
import fa7.socialcode.model.Topico;

@Repository(value = "topicoDao")
public class TopicoDaoHibernate implements TopicoDao {
    
	HibernateTemplate hibernateTemplate;
    //Somente para log
    Log logger = LogFactory.getLog(TopicoDaoHibernate.class);
    
    @Autowired
    public TopicoDaoHibernate (SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

	public Topico findTopico(Long id) {
		Topico topico = (Topico) hibernateTemplate.get(Topico.class, id);
        if (topico == null) {
            throw new ObjectRetrievalFailureException(Topico.class, id);
        }
        return topico;
	}


	public List findTopicos() {
		return hibernateTemplate.find("from Topico");
	}


	public void removeTopico(Long id) {
		hibernateTemplate.delete(findTopico(id));
		
	}


	public void removeTopico(Topico topico) {
		hibernateTemplate.delete(findTopico(topico.getId()));
		
	}


	public void saveTopico(Topico topico) {
		hibernateTemplate.merge(topico);
        if (logger.isDebugEnabled()) {
            logger.debug("topicoId set to: " + topico.getId());
        }
		
	}

	  @Override
	  public Date findDataPostagemById(Long id) {
	    Topico t = (Topico) hibernateTemplate
	      .find("from Topico n where n.id=?", id).get(0);
	    
	    return t.getDataPostagem();
	  }
	
	
}

